<template>
  <Layout>
    <div class="content-header">
      <h2>监控告警</h2>
    </div>
    <div class="content-body">
      <!-- 加载状态 -->
      <div v-if="loading" style="text-align: center; padding: 40px; font-size: 16px; color: var(--text-secondary)">
        加载中...
      </div>

      <!-- 错误提示 -->
      <div v-if="error" style="text-align: center; padding: 40px; font-size: 16px; color: var(--danger-color)">
        {{ error }}
      </div>

      <!-- 数据展示 -->
      <template v-if="!loading && !error">
        <el-card class="stat-cards">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-card danger">
                <div>
                  <div class="stat-label">严重告警</div>
                  <div class="stat-value">{{ criticalCount }} 条</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card warning">
                <div>
                  <div class="stat-label">警告信息</div>
                  <div class="stat-value">{{ warningCount }} 条</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card info">
                <div>
                  <div class="stat-label">提示信息</div>
                  <div class="stat-value">{{ infoCount }} 条</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card success">
                <div>
                  <div class="stat-label">已解决</div>
                  <div class="stat-value">{{ resolvedCount }} 条</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span>告警列表</span>
            </div>
          </template>
          
          <div class="table-toolbar">
            <el-row :gutter="20">
              <el-col :span="5">
                <el-select 
                  v-model="filters.level"
                  placeholder="请选择级别"
                  clearable
                  style="width: 100%"
                >
                  <el-option label="全部" value="all" />
                  <el-option label="严重" value="critical" />
                  <el-option label="警告" value="warning" />
                  <el-option label="提示" value="info" />
                </el-select>
              </el-col>

              <el-col :span="5">
                <el-select 
                  v-model="filters.status"
                  placeholder="请选择状态"
                  clearable
                  style="width: 100%"
                >
                  <el-option label="全部" value="all" />
                  <el-option label="活跃" value="active" />
                  <el-option label="已解决" value="resolved" />
                </el-select>
              </el-col>

              <el-col :span="5">
                <el-select 
                  v-model="filters.type"
                  placeholder="请选择类型"
                  clearable
                  style="width: 100%"
                >
                  <el-option label="全部" value="all" />
                  <el-option 
                    v-for="type in allTypes" 
                    :key="type" 
                    :label="type" 
                    :value="type" 
                  />
                </el-select>
              </el-col>
              
              <el-col :span="5">
                <el-input 
                  v-model="filters.search"
                  placeholder="输入来源或描述"
                  clearable
                />
              </el-col>
              
              <el-col :span="4"> 
                <el-button @click="clearFilters">清除筛选</el-button>                
              </el-col>
            </el-row>
          </div>

          <el-table 
            :data="paginatedAlarms" 
            style="width: 100%" 
            :default-sort="{ prop: 'time', order: 'descending' }"
          >
            <el-table-column 
              prop="time" 
              label="发生时间" 
              sortable 
              :sort-method="(a, b) => new Date(a.time).getTime() - new Date(b.time).getTime()"
            />
            <el-table-column 
              prop="serverName" 
              label="服务器名称" 
              sortable 
              :sort-method="(a, b) => (a.serverName || '').localeCompare(b.serverName || '')"
            >
              <template #default="scope">
                <span v-if="scope.row.serverName" style="font-weight: 600; color: var(--primary-light)">
                  {{ scope.row.serverName }}
                </span>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column 
              prop="serverIP" 
              label="IP地址" 
              sortable 
              :sort-method="(a, b) => (a.serverIP || '').localeCompare(b.serverIP || '')"
            >
              <template #default="scope">
                <span v-if="scope.row.serverIP">{{ scope.row.serverIP }}</span>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column 
              prop="firstTime" 
              label="首次发生时间" 
              sortable 
              :sort-method="(a, b) => new Date(a.firstTime || a.time).getTime() - new Date(b.firstTime || b.time).getTime()"
            >
              <template #default="scope">
                <span v-if="scope.row.firstTime">{{ scope.row.firstTime }}</span>
                <span v-else>{{ scope.row.time }}</span>
              </template>
            </el-table-column>
            <el-table-column 
              prop="duration" 
              label="持续时间" 
              sortable 
              :sort-method="(a, b) => (a.duration || '').localeCompare(b.duration || '')"
            >
              <template #default="scope">
                <span v-if="scope.row.duration">{{ scope.row.duration }}</span>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column prop="level" label="级别" sortable>
              <template #default="scope">
                <el-tag 
                  :type="scope.row.level === 'critical' ? 'danger' : scope.row.level === 'warning' ? 'warning' : 'info'"
                >
                  {{ scope.row.level === 'critical' ? '严重' : scope.row.level === 'warning' ? '警告' : '提示' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column 
              prop="type" 
              label="类型" 
              sortable 
              :sort-method="(a, b) => a.type.localeCompare(b.type)"
            >
              <template #default="scope">
                <span style="font-weight: 500">
                  {{ scope.row.type }}
                </span>
              </template>
            </el-table-column>
            <el-table-column 
              prop="source" 
              label="来源" 
              sortable 
              :sort-method="(a, b) => a.source.localeCompare(b.source)"
            >
              <template #default="scope">
                <span style="font-weight: 600; color: var(--primary-light)">
                  {{ scope.row.source }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="message" label="描述" />
            <el-table-column prop="status" label="状态" sortable>
              <template #default="scope">
                <el-tag 
                  :type="scope.row.status === 'active' ? 'danger' : 'success'"
                >
                  {{ scope.row.status === 'active' ? '活跃' : '已解决' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>

        <!-- 分页组件 -->
        <Pagination
          :current-page="currentPage"
          :total-pages="totalPages"
          :page-size="pageSize"
          :total-items="filteredAlarms.length"
          @page-change="handlePageChange"
          @page-size-change="handlePageSizeChange"
        />      
        </el-card>
      </template>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import Layout from '../components/Layout.vue'
import Pagination from '../components/Pagination.vue'
import { alarmAPI } from '../services/api'
import { useTableData } from '../composables/useTableData'
import type { Alarm } from '../types'

const alarmsData = ref<Alarm[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const sortConfig = ref<{ key: string; direction: 'asc' | 'desc' }>({
  key: 'time',
  direction: 'desc'
})
const filters = ref({
  level: 'all',
  status: 'all',
  type: 'all',
  search: ''
})

// 使用统一的分页逻辑
const {
  currentPage,
  pageSize,
  paginatedData: paginatedAlarms,
  totalPages,
  handlePageChange,
  handlePageSizeChange
} = useTableData({
  data: alarmsData,
  filters,
  defaultSort: { key: 'time', direction: 'desc' },
  pageSize: 5
})

// 加载数据
const fetchAlarms = async () => {
  try {
    loading.value = true
    const response: any = await alarmAPI.getAll()
    if (response.success) {
      alarmsData.value = response.data || []
    } else {
      error.value = '加载数据失败: ' + response.message
    }
    error.value = null
  } catch (err: any) {
    error.value = '加载数据失败: ' + err.message
    console.error('Failed to fetch alarms:', err)
  } finally {
    loading.value = false
  }
}

// 筛选和排序后的数据
const filteredAlarms = computed(() => {
  let filtered = [...alarmsData.value]

  // 级别筛选
  if (filters.value.level !== 'all') {
    filtered = filtered.filter(a => a.level === filters.value.level)
  }

  // 状态筛选
  if (filters.value.status !== 'all') {
    filtered = filtered.filter(a => a.status === filters.value.status)
  }

  // 类型筛选
  if (filters.value.type !== 'all') {
    filtered = filtered.filter(a => a.type === filters.value.type)
  }

  // 搜索筛选
  if (filters.value.search) {
    const searchLower = filters.value.search.toLowerCase()
    filtered = filtered.filter(a => 
      a.source.toLowerCase().includes(searchLower) ||
      a.message.toLowerCase().includes(searchLower)
    )
  }

  // 排序
  if (sortConfig.value.key) {
    filtered.sort((a, b) => {
      const aVal = a[sortConfig.value.key as keyof Alarm]
      const bVal = b[sortConfig.value.key as keyof Alarm]
      
      if (aVal! < bVal!) return sortConfig.value.direction === 'asc' ? -1 : 1
      if (aVal! > bVal!) return sortConfig.value.direction === 'asc' ? 1 : -1
      return 0
    })
  }

  return filtered
})

// 统计数据
const criticalCount = computed(() => alarmsData.value.filter(a => a.level === 'critical' && a.status === 'active').length)
const warningCount = computed(() => alarmsData.value.filter(a => a.level === 'warning' && a.status === 'active').length)
const infoCount = computed(() => alarmsData.value.filter(a => a.level === 'info' && a.status === 'active').length)
const resolvedCount = computed(() => alarmsData.value.filter(a => a.status === 'resolved').length)

// 所有类型
const allTypes = computed(() => [...new Set(alarmsData.value.map(a => a.type).filter(Boolean))])

const clearFilters = () => {
  filters.value = { level: 'all', status: 'all', type: 'all', search: '' }
  sortConfig.value = { key: 'time', direction: 'desc' }
  currentPage.value = 1
}

// 当筛选条件改变时，重置到第一页
const resetPageOnFilterChange = () => {
  currentPage.value = 1
}

computed(() => {
  const _ = [filters.value, sortConfig.value]
  resetPageOnFilterChange()
  return _
})

onMounted(() => {
  fetchAlarms()
})
</script>
